package com.linefly.online_car;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.linefly.online_car.Custom.Custom_Dialog_shaixuan;
import com.linefly.online_car.Custom.Custom_Dialog_zhalan;
import com.linefly.online_car.Custom.MyLoading;
import com.linefly.online_car.Custom.ReLogin;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import Adapter.Adapter_zhalan;
import Been.been_event;
import Util.JsonUtil;
import Util.NavigationBarUtil;
import Util.PreferenceUtil;
import Util.ToastUtil;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Response;

public class Zhalan extends AppCompatActivity {

    private String token_str;//用户的token
    Adapter_zhalan adapter_licheng;
    RecyclerView recyclerView;
    List<String> list;
    ArrayList arrayList_detail;

    View nodata;
    Context context = Zhalan.this;
    String str_mingcheng = "", str_text = "";
    String id = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhalan);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }


        if (NavigationBarUtil.hasNavigationBar(this)) {
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }

        token_str = PreferenceUtil.getString("token", "");
        str_mingcheng = "";
        str_text = "";
        nodata = (View) findViewById(R.id.nodata);
        list = new ArrayList<>();
        arrayList_detail = new ArrayList();
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        EventBus.getDefault().register(context);
        init();


    }

    public void init() {

        list.clear();
        MyLoading.show(context);
        try {
            String url = getString(R.string.url) + "/fence/search";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("token", token_str)
                    .params("name", str_mingcheng)
                    .params("text", str_text)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    ArrayList lists = (ArrayList) hashMap.get("list");
                                    arrayList_detail = (ArrayList) hashMap.get("list");
                                    if (lists.size() > 0) {
                                        for (int i = 0; i < lists.size(); i++) {
                                            HashMap hashMap1 = (HashMap) lists.get(i);
                                            String mingcheng = hashMap1.get("name").toString();

                                            String been = new String(mingcheng);
                                            list.add(been);


                                        }

                                    }


                                } else if (err < 0) {
                                    ReLogin.login(context);
                                } else {
                                    ToastUtil.toast(context, hashMap.get("msg").toString());
                                }

                                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(Zhalan.this);
                                recyclerView.setLayoutManager(linearLayoutManager);
                                adapter_licheng = new Adapter_zhalan(list);
                                recyclerView.setAdapter(adapter_licheng);

                                adapter_licheng.setItemClick(new Adapter_zhalan.item_click() {
                                    @Override
                                    public void itemclick_xiugai(int position) {
                                        //修改
                                        HashMap hashMap1 = (HashMap) arrayList_detail.get(position);
                                        id = hashMap1.get("id").toString();
                                        Intent intent = new Intent(context, Custom_Dialog_zhalan.class);
                                        intent.putExtra("name", hashMap1.get("name").toString());
                                        intent.putExtra("json", hashMap1.get("text").toString());
                                        intent.putExtra("type", "修改");
                                        startActivity(intent);


                                    }

                                    @Override
                                    public void itemclick_shanchu(final int position) {

                                        //删除
                                        new SweetAlertDialog(context)
                                                .setTitleText("确定删除?")
                                                .setConfirmText("确定")
                                                .setCancelText("取消")
                                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                    @Override
                                                    public void onClick(SweetAlertDialog sDialog) {
                                                        sDialog.dismissWithAnimation();
                                                        get_Shanchu(position);

                                                    }
                                                })
                                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                    @Override
                                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                        sweetAlertDialog.dismissWithAnimation();
                                                    }
                                                })
                                                .show();


                                    }


                                });


                                if (list.size() == 0) {
                                    recyclerView.setVisibility(View.GONE);
                                    nodata.setVisibility(View.VISIBLE);
                                } else {
                                    recyclerView.setVisibility(View.VISIBLE);
                                    nodata.setVisibility(View.GONE);
                                }


                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            MyLoading.cancel();
                            Toast.makeText(Zhalan.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void get_Shanchu(int position) {

        HashMap hashMap = (HashMap) arrayList_detail.get(position);

        MyLoading.show(context);
        try {
            String url = getString(R.string.url) + "/fence/delete";

            OkHttpUtils.post(url)
                    .connTimeOut(10000)
                    .params("token", token_str)
                    .params("id", hashMap.get("id").toString())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    init();
                                    ToastUtil.toast(context, hashMap.get("msg").toString());

                                } else {
                                    ToastUtil.toast(context, hashMap.get("msg").toString());
                                }


                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            MyLoading.cancel();
                            Toast.makeText(Zhalan.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void click_shaixuan(View view) {
        final Custom_Dialog_shaixuan custom_dialog_shaixuan = new Custom_Dialog_shaixuan(context, 1);
        custom_dialog_shaixuan.show();
        custom_dialog_shaixuan.setOnClickListener(new Custom_Dialog_shaixuan.OnClickListener() {
            @Override
            public void onClick(String chepai, String shebei) {
                str_mingcheng = chepai;
                init();
                custom_dialog_shaixuan.cancel();


            }
        });


    }

    public void click_xinzeng(View view) {
        //新增
        Intent intent = new Intent(context, Custom_Dialog_zhalan.class);
        intent.putExtra("name", "");
        intent.putExtra("json", "");
        intent.putExtra("type", "新增");
        startActivity(intent);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(been_event been_event) {
        if(been_event.getType().equals("新增")){
            get_Xinzeng_Xiugai(been_event.getName(), been_event.getJson() , 0);
        }else {
            get_Xinzeng_Xiugai(been_event.getName(), been_event.getJson() , 1);
        }
    }

    public void get_Xinzeng_Xiugai(final String name, final String json , int type) {
        MyLoading.show(context);
        try {
            String url = "";
            if (type == 0) {
                url = getString(R.string.url) + "/fence/create";
            } else {
                url = getString(R.string.url) + "/fence/update";
            }

            OkHttpUtils.post(url)
                    .connTimeOut(10000)
                    .params("token", token_str)
                    .params("name", name)
                    .params("text", json)
                    .params("id",id)

                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    str_mingcheng = "";
                                    str_text = "";
                                    init();
                                    ToastUtil.toast(context, hashMap.get("msg").toString());

                                } else {
                                    ToastUtil.toast(context, hashMap.get("msg").toString());
                                }


                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            MyLoading.cancel();
                            Toast.makeText(Zhalan.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void click_back(View view){
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

}
